package com.example.demo09_verifycode.config;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class VerifyCodeFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if ("POST".equalsIgnoreCase(req.getMethod()) && "/login".equals(req.getServletPath())) {
            String code = req.getParameter("code");
            String verifyCode = (String) req.getSession().getAttribute("verify_code");
            // 如果前端传来的验证码和 session 中的不相同，说明校验不通过，拦截请求
            if (!StringUtils.hasText(code) || !code.equalsIgnoreCase(verifyCode)) {
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write("验证码错误");
                return;
            }
        }
        chain.doFilter(request, response);

    }
}
